package erlwitch.parser.reader;

import java.io.IOException;
import java.io.Reader;

public class SpecialReader extends Reader {

	private Reader baseReader = null;
	private boolean returnMinusOne = false;
	
	public SpecialReader(Reader baseReader) {
		this.baseReader = baseReader;
	}
	
	@Override
	public void close() throws IOException {
		baseReader.close();
	}

	@Override
	public int read(char[] cbuf, int off, int len) throws IOException {
		int c = baseReader.read();
		if (c==-1 && !returnMinusOne) {
			char c1 = '\n';
			cbuf[off] = c1;
			returnMinusOne = true;
			return 1;	
		} else if (c==-1 && returnMinusOne) {
			return -1;
		} else {
			cbuf[off] = (char)c;
			int ret = baseReader.read(cbuf, off+1, len-1);
			/*en la siguiente invocacion de read va a dar -1, y se retornara el '\n'*/
			if (ret==-1) returnMinusOne = true;
			return ret+1;
		}
	}
}
